package controller

import (
    "strings"
    
    "github.com/gin-gonic/gin"
    
    "collecter/app/common/enum"
    "collecter/app/common/helper"
)

type AnnexController struct {
    BaseController
}

//
// Upload
//  @Description: 上传文件到服务器本地
//  @receiver c
//  @param ctx
//
func (c *AnnexController) Upload(ctx *gin.Context) {
    type inType struct {
        Index  string `json:"index,omitempty"`  // 文件上传表单中，文件域名称
        UpType string `json:"up_type,omitempty"`    // 上传文件的类型，image、file、video、voices、other
    }
    var inData inType
    if err := ctx.BindJSON(&inData); err != nil {
        c.FormatReturn(enum.FAILED, "", err.Error())
    }
    if len(inData.Index) == 0 {
        inData.Index = enum.FILE_TYPE_IMAGE
    }
    fileTypeMap := enum.GetFileTypeMap()
    if _, ok := fileTypeMap[inData.UpType]; !ok {
        c.FormatReturn(6, "", "文件类型不允许")
    }
    file, fileHeader, err := ctx.Request.FormFile(inData.Index)
    if err != nil {
        c.FormatReturn(enum.FAILED, "", err.Error())
    }
    upFile := helper.UpFile{}
    upFile.FilePointer = file
    upFile.Headers = fileHeader
    upFile.IsRename = true
    upFile.UploadType = inData.UpType
    if rst, err := upFile.Upload(); err != nil {
        c.FormatReturn(enum.FAILED, "", err.Error())
    } else {
        hostInfo := c.GetHostInfo()
        url := strings.TrimRight(hostInfo["domain"], "/") + "/" + strings.Trim(rst.Url, "/")
        c.FormatReturn(enum.SUCCESS, url)
    }
}


